package ro.fortech.peaa.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import ro.fortech.peaa.domain.Employee;
import ro.fortech.peaa.domain.Job;
import ro.fortech.peaa.service.api.IEmployeeManager;
import ro.fortech.peaa.service.api.IJobManager;


/**
 * Handles the requests related to an employee.
 * 
 * @author andrei
 *
 */
public class EmployeeDetailsController extends AbstractController {

	private IEmployeeManager employeeManager;

	private IJobManager jobManager;

	/**
	 * @param employeeManager the employeeManager to set
	 */
	public void setEmployeeManager(IEmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	/**
	 * @param jobsManager the jobsManager to set
	 */
	public void setJobManager(IJobManager jobsManager) {
		this.jobManager = jobsManager;
	}

	/**
	 * Handles the GET request to show details about an employee.
	 * Also handles the POST request that will update the details for a particular empolyee.
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String errorMessage = "";
		Employee emp = null;
		try {
			String method = request.getMethod();
			logger.info("Method: " + method);
			// get id from request
			String idStr = request.getParameter("id");
			logger.info(idStr);
			Integer id = -1;
			if (idStr != null && !"".equals(idStr)) {
				id = Integer.valueOf(idStr);
			}
			// get employee by id
			emp = this.employeeManager.find(id);

			if (method.equals(METHOD_GET)) {
				Map<String, Object> map = new HashMap<String, Object>();
				if (emp != null) {
					map.put("employee", emp);
				}
				// Get all jobs, but only with id and title set
				List<Job> jobs = jobManager.findAllIdAndTitle();
				map.put("jobs", jobs);
				return new ModelAndView("employee_details", map);
			} else {
				boolean employeeModified = false;
				String jobId = request.getParameter("job_id");
				if (jobId != null && !jobId.equals("")) {
					emp.setJobId(jobId);
					employeeModified = true;
				} else {
					errorMessage += " Job id is empty!"; 
				}

				String firstName = request.getParameter("first_name");
				if (firstName != null && !firstName.equals("")) {
					emp.setFirstName(firstName);
					employeeModified = true;
				}
				String lastName = request.getParameter("last_name");
				if (lastName != null && !lastName.equals("")) {
					emp.setLastName(lastName);
					employeeModified = true;
				} else {
					errorMessage += " Last name is empty!";
				}
				String email = request.getParameter("email");
				if (email != null && !email.equals("")) {
					emp.setEmail(email);
					employeeModified = true;
				} else {
					errorMessage += "Email is empty!";
				}
				String phone = request.getParameter("phone");
				if (phone != null && !phone.equals("")) {
					emp.setPhoneNumber(phone);
					employeeModified = true;
				}
				String hireDate = request.getParameter("hire_date");
				if (hireDate != null && !hireDate.equals("")) {
					DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
					emp.setHireDate(dateFormat.parse(hireDate));
					employeeModified = true;
				} else { 
					errorMessage += " Hire date is empty!";
				}
				String salary = request.getParameter("salary");
				if (salary != null && !salary.equals("")) {
					emp.setSalary(Double.parseDouble(salary));
					employeeModified = true;
				}
				String commissionPct = request.getParameter("commission_pct");
				if (commissionPct != null && !commissionPct.equals("")) {
					emp.setCommissionPct(Double.parseDouble(commissionPct));
					employeeModified = true;
				}
				String managerId = request.getParameter("manager_id");
				if (managerId != null && !managerId.equals("")) {
					emp.setManagerId(Integer.parseInt(managerId));
					employeeModified = true;
				}
				String departmentId = request.getParameter("department_id");
				if (departmentId != null && !departmentId.equals("")) {
					emp.setDepartmentId(Integer.parseInt(departmentId));
					employeeModified = true;
				}

				if (errorMessage.equals("")) {
				if (employeeModified) {
					logger.info("Updating employee.");
					employeeManager.updateEmployee(emp);
					logger.info("Updated employee.");
				}
				}else {
					logger.info("Cannot update employee due to some issues: " + errorMessage);
					throw new Exception(errorMessage);
				}
			}

		} catch (Exception e) {
			logger.info("Failure in employee details: " + e.getMessage());
			Map<String, Object> map = new HashMap<String, Object>();
			if (emp != null) {
				map.put("employee", emp);
			}
			// Get all jobs
			List<Job> jobs = jobManager.findAllIdAndTitle();
			map.put("jobs", jobs);
			map.put("error_message", e.getMessage());
			return new ModelAndView("employee_details", map);


		}
		// Load employees
		Map<String, Object> map = new HashMap<String, Object>();
		List<Employee> employees = this.employeeManager.findAll();
		logger.info("Found " + employees.size() + " employees.");
		map.put("employees", employees);
		map.put("average_salary", employeeManager.getAverageSalary());
		return new ModelAndView("employees", map);

	}
}
